package com.ac.api.component.controller;

import com.base.annotation.Unsecured;
import com.ac.api.component.entity.CpModule;
import com.ac.api.component.service.CpModuleService;
import com.ac.api.component.vo.CpLabelTree;
import com.ac.api.component.vo.CpLabelVo;
import com.ac.api.component.vo.MoudleTree;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.component.entity.CpLabel;
import com.ac.api.component.service.CpLabelService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gjj
 * @since 2024-10-26
 */
@Api(tags = "标签管理")
@RestController
@RequestMapping("/cpLabel")
public class CpLabelController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(CpLabelController.class);
        @Autowired
        private              CpLabelService entityService;
        @Autowired
        private CpModuleService cpModuleService;
        @ApiOperation(value = "查询模块下的标签")
        @RequestMapping(value = "/moduleid/{moduleid}", method = {RequestMethod.GET})
        @ApiImplicitParam(name = "moduleid", value = "模块ID", required = true, paramType = "path")
        @Unsecured
        public Result getLabelById(@PathVariable final Integer moduleid) {
            try {
                List<CpLabel> CpLabels = entityService.lambdaQuery()
                        .eq(CpLabel::getModuleid, moduleid)
                        .eq(CpLabel::getState,"t")
                        .orderByAsc(CpLabel::getOrderNum).list();
                return new Result(true, CpLabels);
            } catch (Exception e) {
                LOG.error("查询单个标签失败", e);
                return new Result(false, new CpLabel());
            }
        }

        @ApiOperation(value = "查询父标签下的标签")
        @RequestMapping(value = "/labelId/{labelId}", method = {RequestMethod.GET})
        @ApiImplicitParam(name = "labelId", value = "标签ID", required = true, paramType = "path")
        @Unsecured
        public Result getLabelByLabelId(@PathVariable final Integer labelId) {
            try {
                List<CpLabel> CpLabels = entityService.lambdaQuery()
                        .eq(CpLabel::getParentid, labelId)
                        .eq(CpLabel::getState,"t")
                        .orderByAsc(CpLabel::getOrderNum).list();
                return new Result(true, CpLabels);
            } catch (Exception e) {
                LOG.error("查询单个标签失败", e);
                return new Result(false, new CpLabel());
            }
        }

        @SysLog(action = "findByPage", value = "分页查询标签")
        @ApiOperation(value = "分页查询标签", notes = "分页查询标签")
        @RequestMapping(method = RequestMethod.GET)
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<CpLabelVo>> findByPage(final CpLabelVo example, final Page page) {
            IPage<CpLabelVo>        records    = entityService.findByPage(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "one", value = "查询单个标签")
        @ApiOperation(value = "查询单个标签")
        @RequestMapping(value = "{id}", method = {RequestMethod.GET})
        @ApiImplicitParam(name = "id", value = "标签ID", required = true, paramType = "path")
        public Result one(@PathVariable final Integer id) {
            try {
                CpLabel entity = entityService.getLabelById(id);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询单个标签失败", e);
                return new Result(false, new CpLabel());
            }
        }

        @SysLog(action = "delete", value = "删除标签")
        @ApiOperation(value = "删除标签")
        @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
        @ApiImplicitParam(name = "id", value = "标签ID", required = true, paramType = "path")
        public Result delete(@PathVariable final Integer id) {
            try {
                entityService.lambdaUpdate().set(CpLabel::getState, "f").eq(CpLabel::getId,id).update();
                return new Result(true, "成功删除标签", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除标签失败", e);
                return new Result(false, "删除标签失败", "该标签不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除标签失败", e);
                return new Result(false, "删除标签失败", e.getMessage());
            }
        }



        @SysLog(action = "add", value = "添加标签")
        @ApiOperation(value = "添加标签")
        @RequestMapping(method = {RequestMethod.POST})
        public Result add(@Valid @RequestBody final CpLabel entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存标签失败", errorMsg, map);
                } else {
                    entity.setCreatetime(new Date());
                    entity.setState("t");
                    entityService.save(entity);
                    return new Result(true, "成功保存标签", null);
                }
            } catch (Exception e) {
                LOG.error("添加标签失败", e);
                return new Result(false, "保存标签失败", e.getMessage());
            }
        }

        @SysLog(action = "update", value = "修改标签")
        @ApiOperation(value = "修改标签")
        @RequestMapping(method = {RequestMethod.PUT})
        public Result update(@Valid @RequestBody final CpLabel entity, final BindingResult result) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "修改标签失败", errorMsg, map);
                } else {
                    if (null == entity.getId()) {
                         throw new RuntimeException("id不能为空");
                    }
                    entityService.updateById(entity);
                    return new Result(true, "成功修改标签", null);
                }
            } catch (Exception e) {
                LOG.error("修改标签失败", e);
                return new Result(false, "修改标签失败", e.getMessage());
            }
        }

        @ApiOperation(value = "全部标签")
        @RequestMapping(value = "all", method = RequestMethod.GET)
        public Result<List<MoudleTree>> all() {
            List<CpLabel> cpLabels = entityService.lambdaQuery().eq(CpLabel::getState,"t").list();
            List<CpLabelTree> trees=new ArrayList<>();
            for (CpLabel cpLabel :cpLabels){
                CpLabelTree cpLabelTree=new CpLabelTree();
                BeanUtils.copyProperties(cpLabel,cpLabelTree);
                trees.add(cpLabelTree);
            }
            //获取父节点
            List<CpLabelTree> collect = trees.stream().filter(m -> m.getParentid() == 0).map(
                    (m) -> {
                        m.setChildren(entityService.getChildrenList(m, trees));
                        return m;
                    }
            ).collect(Collectors.toList());
            List<CpModule> cpModules=cpModuleService.lambdaQuery().eq(CpModule::getState,"t").list();
            List<MoudleTree> moudleTrees=new ArrayList<>();
            for (CpModule cpModule:cpModules){
                MoudleTree moudleTree=new MoudleTree();
                moudleTree.setCpModule(cpModule);
                List<CpLabelTree> cpLabelTree =new ArrayList<>();
                for (CpLabelTree cpLabeltree:collect){
                    if (cpLabeltree.getModuleid()==cpModule.getId()){
                        cpLabelTree.add(cpLabeltree);
                    }
                }
                moudleTree.setCpLabelTree(cpLabelTree);
                moudleTrees.add(moudleTree);
            }
            return new Result<>(true,moudleTrees);
        }

}

